package org.justdroid.justdroid;

import java.lang.reflect.Method;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.TelephonyManager;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.internal.telephony.ITelephony;

public class CallingScreen extends Activity {
	private String callerDetails, number;
	private TextView recipientTextView;
	private BroadcastReceiver bReceiver;
	private GestureDetector gestureDetector;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_calling);
		recipientTextView = (TextView) findViewById(R.id.recipientTextView);
		gestureDetector = new GestureDetector(getApplicationContext(), new GestureListener());
		
		if(getIntent().getExtras() != null) {
			if(Utils.callingDetails != null && Utils.callingDetails.get("name") != null) {
				//Retrieve the name of the recipient and the type of the number from the Bundle
				String name = Utils.callingDetails.get("name");
				String typeOfNumber = Utils.callingDetails.get("type");
				if(getIntent().getExtras().getInt("type",-1) == Utils.OUTGOING) {
					//outgoing call
					callerDetails = "Calling " + name + ": " + typeOfNumber;
				}
				else {
					//incoming call
					callerDetails = "Call from " + name + ": " + typeOfNumber;
				}
			}
			else if(Utils.callingDetails != null) {
				//Retrieve the name of the recipient and the type of the number from the Bundle
				if(getIntent().getExtras().getInt("type",-1) == Utils.OUTGOING) {
					//outgoing call
					callerDetails = "Calling " + Utils.callingDetails.get("number");;
				}
				else {
					//incoming call
					callerDetails = "Call from " + Utils.callingDetails.get("number");;
				}
			}
			if(Utils.callingDetails != null)
			{
				this.number =  Utils.callingDetails.get("number");
				displayCall(callerDetails, Utils.callingDetails.get("number"));
			}
		}
		else
		{
			recipientTextView.setText("Error!");
		}
		
		this.bReceiver = new BroadcastReceiver() {
		    @Override
		    public void onReceive(Context context, Intent intent) {
		        if(intent.getAction().equals(Utils.CALL_ENDED)) {
		        	if(Utils.isAccessibilityEnabled(getApplicationContext()))
		        		TTS.speak(intent.getExtras().getString("message"));
		        	Toast.makeText(getApplicationContext(), intent.getExtras().getString("message"), Toast.LENGTH_SHORT).show();
		        	//inform user - tts
		           //check if there is any active call (no. of calls); if so, activate the current call,
		              if(Utils.off_hook == 1 || Utils.ringing == 1) {
		    			  
		    		  }
		    		  else {
		    			  //All calls ended, finish activity
		    			  finish();
		    			  Utils.off_hook = 0;
		    		  }
		    		 
		        }
		    }
		};
		
	}
	
	public static void announceCaller(String details, String number) {
			TTS.speak(details);
	}
	
	 @Override
	 public boolean onKeyDown(int keyCode, KeyEvent event) {
		//long press of power button will end the call
		 if(KeyEvent.KEYCODE_POWER == event.getKeyCode()){
	    	 TelephonyManager telephony = (TelephonyManager) getApplicationContext()
	                    .getSystemService(Context.TELEPHONY_SERVICE);
	            try {
	                Class<?> c = Class.forName(telephony.getClass().getName());
	                Method m = c.getDeclaredMethod("getITelephony");
	                m.setAccessible(true);
	                ITelephony telephonyService = (ITelephony) m.invoke(telephony);
	                telephonyService.endCall();
	            }
	            catch(Exception e) {
	            	e.printStackTrace();
	            }
	          return true; 
	          }
		 else if(keyCode == KeyEvent.KEYCODE_BACK) {
			 //do nothing
		       return true;
		    }
	     return super.onKeyDown(keyCode, event);
	 }
	 
	 @Override
	 public boolean onKeyUp(int keyCode, KeyEvent event) {
		 if(KeyEvent.KEYCODE_VOLUME_UP == event.getKeyCode()){
			 if(Utils.ringing == 1) {
				 //announce the caller name/number
				 announceCaller(this.callerDetails, this.number);
				 return true;
			 }
			 else if(Utils.ringing == 0 && Utils.off_hook == 1) {
				 //activate loudspeaker
				 Utils.audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
				 if(Utils.audioManager.isSpeakerphoneOn() == false) {
					 Utils.audioManager.setSpeakerphoneOn(true);
				 }
				 else {
					//deactivate loudspeaker
					 Utils.audioManager.setSpeakerphoneOn(false);
				 }
				 return true;
			 }
	     }
		 else if(KeyEvent.KEYCODE_VOLUME_DOWN == event.getKeyCode()){
			 if(Utils.ringing == 1) {
			 	//mute the ringtone
			 	muteRingtone();
			 	return true;
	         }
			 else if(Utils.ringing == 0 && Utils.off_hook == 1) {
				
				 if(Utils.audioManager.isMicrophoneMute() == true) {
					 Utils.audioManager.setMicrophoneMute(false);
				 }
				 else {
					 Utils.audioManager.setMicrophoneMute(true);
				 }
				return true;
			 }
		 }
	     return super.onKeyUp(keyCode, event);
	 }
	 
	 
	 public static void muteRingtone() {
		 if(Utils.ringtone.isPlaying()) {
			 //mute
			 Utils.ringtone.stop();
		 }
	}
	
	public void displayCall(String details, String number) {
		recipientTextView.setText(details);
		recipientTextView.setContentDescription(details);	
		
		//store outgoing call details
		if(!Utils.numbers.contains(number)) {
			Utils.numbers.add(number);
			Utils.callers.add(callerDetails);
		}
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		LocalBroadcastManager.getInstance(this).registerReceiver((this.bReceiver), new IntentFilter(Utils.CALL_ENDED));
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent e) {
	    return gestureDetector.onTouchEvent(e);
	}
	
	private class GestureListener extends GestureDetector.SimpleOnGestureListener {

	    @Override
	    public boolean onDown(MotionEvent e) {
	        return true;
	    }
	    // event when double tap occurs
	    @Override
	    public boolean onDoubleTap(MotionEvent e) {
	       //user wants to type a number
	      Intent intent = new Intent(getBaseContext(), PhoneDialerApp.class);
      	  intent.putExtra("flag", 1);
      	  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      	  startActivity(intent);
	      return true;
	    }
	    
	    @Override
	    public void onLongPress(MotionEvent e) {
	    	//make a new call
	    	Intent intent = new Intent(getBaseContext(), PhoneDialerApp.class);
      	  	intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      	  	startActivity(intent);
	    }
	}
	
	@Override
	public void onResume() {
		super.onResume();
		//get the root layout
		LinearLayout layout = (LinearLayout) findViewById(R.id.calling);
		Utils.applyFontColorChanges(getApplicationContext(), layout);  Utils.applyFontSizeChanges(getApplicationContext(), layout);  Utils.applyFontTypeChanges(getApplicationContext(), layout);
	}
}